<!DOCTYPE html>



  


<html class="theme-next pisces use-motion" lang="">
<head>
  <meta charset="UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=edge" />
<meta name="viewport" content="width=device-width, initial-scale=1, maximum-scale=1"/>
<meta name="theme-color" content="#222">









<meta http-equiv="Cache-Control" content="no-transform" />
<meta http-equiv="Cache-Control" content="no-siteapp" />
















  
  
  <link href="/blog/lib/fancybox/source/jquery.fancybox.css?v=2.1.5" rel="stylesheet" type="text/css" />







<link href="/blog/lib/font-awesome/css/font-awesome.min.css?v=4.6.2" rel="stylesheet" type="text/css" />

<link href="/blog/css/main.css?v=5.1.4" rel="stylesheet" type="text/css" />


  <link rel="apple-touch-icon" sizes="180x180" href="/blog/images/apple-touch-icon-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="32x32" href="/blog/images/favicon-32x32-next.png?v=5.1.4">


  <link rel="icon" type="image/png" sizes="16x16" href="/blog/images/favicon-16x16-next.png?v=5.1.4">


  <link rel="mask-icon" href="/blog/images/logo.svg?v=5.1.4" color="#222">





  <meta name="keywords" content="Hexo, NexT" />










<meta name="description" content="####1. 文件上传 ######1). 主要是CommonsMultipartResolver解析器依赖commons-fileupload和commons-io这两个jar包commons-fileupload-1.3.3.jarcommons-io-2.6.jar">
<meta name="keywords" content="Android、iOS、Web、React Native">
<meta property="og:type" content="article">
<meta property="og:title" content="JakartaEE-Spring、MyBatis和SpringMVC的整合(三)">
<meta property="og:url" content="http://yoursite.com/blog/2018/08/06/JakartaEE-Framework/JakartaEE-Spring、MyBatis和SpringMVC的整合(三)/index.html">
<meta property="og:site_name" content="凌浩雨_博客">
<meta property="og:description" content="####1. 文件上传 ######1). 主要是CommonsMultipartResolver解析器依赖commons-fileupload和commons-io这两个jar包commons-fileupload-1.3.3.jarcommons-io-2.6.jar">
<meta property="og:locale" content="default">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-6d64a4311b166176.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-2f93f1bd33960a02.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-8ef53258b81e5478.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-29b2fad22fce1650.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-028e20226d02408d.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-7c6a436152ab3f6c.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-73ddda57215f390b.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-ab21f0646adb004e.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-1f759be09528ae9d.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-26be10e5f91dcd43.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-fe001ee78bf49fa6.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-8d3b3d1c10de4620.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-0b208ca49a4c7ba1.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-0c254a7ab0a561a1.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-6382fa8057a4cca0.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-a3425b8471ed00c6.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-4dafc229ef664840.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-32dcf92e1629861c.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:image" content="https://upload-images.jianshu.io/upload_images/3110861-e848fb394875a2ae.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">
<meta property="og:updated_time" content="2018-08-06T10:50:55.393Z">
<meta name="twitter:card" content="summary">
<meta name="twitter:title" content="JakartaEE-Spring、MyBatis和SpringMVC的整合(三)">
<meta name="twitter:description" content="####1. 文件上传 ######1). 主要是CommonsMultipartResolver解析器依赖commons-fileupload和commons-io这两个jar包commons-fileupload-1.3.3.jarcommons-io-2.6.jar">
<meta name="twitter:image" content="https://upload-images.jianshu.io/upload_images/3110861-6d64a4311b166176.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240">



<script type="text/javascript" id="hexo.configurations">
  var NexT = window.NexT || {};
  var CONFIG = {
    root: '/blog/',
    scheme: 'Pisces',
    version: '5.1.4',
    sidebar: {"position":"left","display":"post","offset":12,"b2t":false,"scrollpercent":false,"onmobile":false},
    fancybox: true,
    tabs: true,
    motion: {"enable":true,"async":false,"transition":{"post_block":"fadeIn","post_header":"slideDownIn","post_body":"slideDownIn","coll_header":"slideLeftIn","sidebar":"slideUpIn"}},
    duoshuo: {
      userId: '0',
      author: 'Author'
    },
    algolia: {
      applicationID: '',
      apiKey: '',
      indexName: '',
      hits: {"per_page":10},
      labels: {"input_placeholder":"Search for Posts","hits_empty":"We didn't find any results for the search: ${query}","hits_stats":"${hits} results found in ${time} ms"}
    }
  };
</script>



  <link rel="canonical" href="http://yoursite.com/blog/2018/08/06/JakartaEE-Framework/JakartaEE-Spring、MyBatis和SpringMVC的整合(三)/"/>





  <title>JakartaEE-Spring、MyBatis和SpringMVC的整合(三) | 凌浩雨_博客</title>
  








</head>

<body itemscope itemtype="http://schema.org/WebPage" lang="default">

  
  
    
  

  <div class="container sidebar-position-left page-post-detail">
    <div class="headband"></div>

    <header id="header" class="header" itemscope itemtype="http://schema.org/WPHeader">
      <div class="header-inner"><div class="site-brand-wrapper">
  <div class="site-meta ">
    

    <div class="custom-logo-site-title">
      <a href="/blog/"  class="brand" rel="start">
        <span class="logo-line-before"><i></i></span>
        <span class="site-title">凌浩雨_博客</span>
        <span class="logo-line-after"><i></i></span>
      </a>
    </div>
      
        <p class="site-subtitle"></p>
      
  </div>

  <div class="site-nav-toggle">
    <button>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
      <span class="btn-bar"></span>
    </button>
  </div>
</div>

<nav class="site-nav">
  

  
    <ul id="menu" class="menu">
      
        
        <li class="menu-item menu-item-home">
          <a href="/blog/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-home"></i> <br />
            
            Home
          </a>
        </li>
      
        
        <li class="menu-item menu-item-archives">
          <a href="/blog/archives/" rel="section">
            
              <i class="menu-item-icon fa fa-fw fa-archive"></i> <br />
            
            Archives
          </a>
        </li>
      

      
    </ul>
  

  
</nav>



 </div>
    </header>

    <main id="main" class="main">
      <div class="main-inner">
        <div class="content-wrap">
          <div id="content" class="content">
            

  <div id="posts" class="posts-expand">
    

  

  
  
  

  <article class="post post-type-normal" itemscope itemtype="http://schema.org/Article">
  
  
  
  <div class="post-block">
    <link itemprop="mainEntityOfPage" href="http://yoursite.com/blog/blog/2018/08/06/JakartaEE-Framework/JakartaEE-Spring、MyBatis和SpringMVC的整合(三)/">

    <span hidden itemprop="author" itemscope itemtype="http://schema.org/Person">
      <meta itemprop="name" content="凌浩雨">
      <meta itemprop="description" content="">
      <meta itemprop="image" content="/blog/images/avatar.jpeg">
    </span>

    <span hidden itemprop="publisher" itemscope itemtype="http://schema.org/Organization">
      <meta itemprop="name" content="凌浩雨_博客">
    </span>

    
      <header class="post-header">

        
        
          <h1 class="post-title" itemprop="name headline">JakartaEE-Spring、MyBatis和SpringMVC的整合(三)</h1>
        

        <div class="post-meta">
          <span class="post-time">
            
              <span class="post-meta-item-icon">
                <i class="fa fa-calendar-o"></i>
              </span>
              
                <span class="post-meta-item-text">Posted on</span>
              
              <time title="Post created" itemprop="dateCreated datePublished" datetime="2018-08-06T18:01:38+08:00">
                2018-08-06
              </time>
            

            

            
          </span>

          

          
            
          

          
          

          

          

          

        </div>
      </header>
    

    
    
    
    <div class="post-body" itemprop="articleBody">

      
      

      
        <p>####1. 文件上传</p>
<p>######1). 主要是CommonsMultipartResolver解析器依赖commons-fileupload和commons-io这两个jar包<br><a href="http://commons.apache.org/proper/commons-fileupload/download_fileupload.cgi" target="_blank" rel="noopener">commons-fileupload-1.3.3.jar</a><br><a href="http://commons.apache.org/proper/commons-io/download_io.cgi" target="_blank" rel="noopener">commons-io-2.6.jar</a><br><a id="more"></a></p>
<p>######2). 修改editItem.jsp如下<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br></pre></td><td class="code"><pre><span class="line">&lt;%@ page language=&quot;java&quot; contentType=&quot;text/html; charset=UTF-8&quot; pageEncoding=&quot;UTF-8&quot;%&gt;</span><br><span class="line">&lt;%@ taglib uri=&quot;http://java.sun.com/jsp/jstl/core&quot; prefix=&quot;c&quot;%&gt;</span><br><span class="line">&lt;%@ taglib uri=&quot;http://java.sun.com/jsp/jstl/fmt&quot; prefix=&quot;fmt&quot; %&gt;</span><br><span class="line">&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD HTML 4.01 Transitional//EN&quot; &quot;http://www.w3.org/TR/html4/loose.dtd&quot;&gt;</span><br><span class="line">&lt;html&gt;</span><br><span class="line">	&lt;head&gt;</span><br><span class="line">		&lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=UTF-8&quot;&gt;</span><br><span class="line">		&lt;title&gt;修改商品信息&lt;/title&gt;</span><br><span class="line">	&lt;/head&gt;</span><br><span class="line">	&lt;body&gt;</span><br><span class="line">		&lt;!-- 上传图片是需要指定属性 enctype=&quot;multipart/form-data&quot; --&gt;</span><br><span class="line">	    </span><br><span class="line">	    &lt;%-- &lt;form id=&quot;itemForm&quot; action=&quot;$&#123;pageContext.request.contextPath &#125;/updateItem.action&quot; method=&quot;post&quot;&gt; --%&gt;</span><br><span class="line">	    &lt;form id=&quot;itemForm&quot; action=&quot;$&#123;pageContext.request.contextPath &#125;/updateItem.action&quot; </span><br><span class="line">	    method=&quot;post&quot; enctype=&quot;multipart/form-data&quot;&gt;</span><br><span class="line">	    	&lt;input type=&quot;hidden&quot; name=&quot;id&quot; value=&quot;$&#123;item.id &#125;&quot;/&gt;修改商品信息：</span><br><span class="line">	    	&lt;table width=&quot;100%&quot; border=&quot;1&quot;&gt;</span><br><span class="line">	    		&lt;tr&gt;</span><br><span class="line">	    			&lt;td&gt;商品名称&lt;/td&gt;</span><br><span class="line">	    			&lt;td&gt;&lt;input type=&quot;text&quot; name=&quot;name&quot; value=&quot;$&#123;item.name &#125;&quot;/&gt;&lt;/td&gt;</span><br><span class="line">	    		&lt;/tr&gt;</span><br><span class="line">	    		&lt;tr&gt;</span><br><span class="line">	    			&lt;td&gt;商品价格&lt;/td&gt;</span><br><span class="line">	    			&lt;td&gt;&lt;input type=&quot;text&quot; name=&quot;price&quot; value=&quot;$&#123;item.price &#125;&quot;/&gt;&lt;/td&gt;</span><br><span class="line">	    		&lt;/tr&gt;</span><br><span class="line">	    		&lt;tr&gt;</span><br><span class="line">	    			&lt;td&gt;商品生产日期&lt;/td&gt;</span><br><span class="line">	    			&lt;td&gt;&lt;input type=&quot;text&quot; name=&quot;createtime&quot; </span><br><span class="line">	    			value=&quot;&lt;fmt:formatDate value=&quot;$&#123;item.createtime&#125;&quot; pattern=&quot;yyyy-MM-dd HH:mm:ss&quot;/&gt;&quot;/&gt;</span><br><span class="line">	    			&lt;/td&gt;</span><br><span class="line">	    		&lt;/tr&gt;</span><br><span class="line">	    		&lt;tr&gt;</span><br><span class="line">	    			&lt;td&gt;商品图片&lt;/td&gt;</span><br><span class="line">	    			&lt;td&gt;</span><br><span class="line">	    				&lt;c:if test=&quot;$&#123;item.pic != null &#125;&quot;&gt;</span><br><span class="line">	    					&lt;img src=&quot;/pic/$&#123;item.pic &#125;&quot; width=&quot;100&quot; height=&quot;100&quot;/&gt;</span><br><span class="line">	    					&lt;br&gt;</span><br><span class="line">	    				&lt;/c:if&gt;</span><br><span class="line">	    				&lt;input type=&quot;file&quot; name=&quot;picture&quot;/&gt;</span><br><span class="line">	    			&lt;/td&gt;</span><br><span class="line">	    		&lt;/tr&gt;</span><br><span class="line">	    		&lt;tr&gt;</span><br><span class="line">	    			&lt;td&gt;商品简介&lt;/td&gt;</span><br><span class="line">	    			&lt;td&gt;&lt;textarea rows=&quot;3&quot; cols=&quot;30&quot; name=&quot;detail&quot;&gt;$&#123;item.detail &#125;&lt;/textarea&gt;&lt;/td&gt;</span><br><span class="line">	    		&lt;/tr&gt;</span><br><span class="line">	    		&lt;tr&gt;</span><br><span class="line">	    			&lt;td colspan=&quot;2&quot; align=&quot;center&quot;&gt;</span><br><span class="line">	    				&lt;input type=&quot;submit&quot; value=&quot;提交&quot;/&gt;</span><br><span class="line">	    			&lt;/td&gt;</span><br><span class="line">	    		&lt;/tr&gt;</span><br><span class="line">	    	&lt;/table&gt;</span><br><span class="line">	    </span><br><span class="line">	    &lt;/form&gt;</span><br><span class="line">	&lt;/body&gt;</span><br><span class="line">&lt;/html&gt;</span><br></pre></td></tr></table></figure></p>
<p><img src="https://upload-images.jianshu.io/upload_images/3110861-6d64a4311b166176.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图1.png"></p>
<p>######3). 多部件类型multipart解析<br>在springmvc.xml文件中添加：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">&lt;!-- 配置多媒体文件解析器 --&gt;</span><br><span class="line">&lt;!-- 文件上传 --&gt;</span><br><span class="line">&lt;bean id=&quot;multipartResolver&quot;</span><br><span class="line">	class=&quot;org.springframework.web.multipart.commons.CommonsMultipartResolver&quot;&gt;</span><br><span class="line">	&lt;!-- 设置上传文件的最大尺寸为5MB --&gt;</span><br><span class="line">	&lt;property name=&quot;maxUploadSize&quot;&gt;</span><br><span class="line">		&lt;value&gt;5242880&lt;/value&gt;</span><br><span class="line">	&lt;/property&gt;</span><br><span class="line">&lt;/bean&gt;</span><br></pre></td></tr></table></figure></p>
<p>######4). 创建文件保存的虚拟目录<br>在上传文件之前，首先要创建一个虚拟目录来保存文件，这个虚拟目录会对应磁盘上的一个实际的目录，在实际开发中肯定会有一个服务器专门存储资源的，在这里我们就用本地磁盘来保存文件，然后映射一个虚拟目录，用来在程序中指定获取文件的路径.<br>I. 先在Tomcat上点击右键选择clean…，完成之后再双击Tomcat。<br><img src="https://upload-images.jianshu.io/upload_images/3110861-2f93f1bd33960a02.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图2.png"></p>
<p>II. 选择下方的Modules。<br><img src="https://upload-images.jianshu.io/upload_images/3110861-8ef53258b81e5478.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图3.png"></p>
<p>III. 点击Add External Web Module…<br><img src="https://upload-images.jianshu.io/upload_images/3110861-29b2fad22fce1650.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图4.png"></p>
<p>IV.  Document base选择本机目录，Path添加虚拟目录，在editItem.jsp中是/pic<br><img src="https://upload-images.jianshu.io/upload_images/3110861-028e20226d02408d.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图5.png"><br><img src="https://upload-images.jianshu.io/upload_images/3110861-7c6a436152ab3f6c.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图6.png"></p>
<p>V. 点击确定后，如图：<br><img src="https://upload-images.jianshu.io/upload_images/3110861-73ddda57215f390b.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图7.png"></p>
<p>VI. 第二种方法就是在tomcat的配置文件中配置一下，配置文件位置在tomcat目录/conf/server.xml中：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&lt;Context docBase=&quot;D:\picture&quot; path=&quot;/pic&quot; reloadable=&quot;true&quot;/&gt;</span><br></pre></td></tr></table></figure></p>
<p><img src="https://upload-images.jianshu.io/upload_images/3110861-ab21f0646adb004e.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图8.png"></p>
<p>######5). 后台Controller方法<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">	@RequestMapping(value = &quot;/updateItem&quot;, method = &#123; RequestMethod.POST, RequestMethod.GET &#125;)</span><br><span class="line">	public String updateItem(Item item, MultipartFile picture) throws Exception &#123;</span><br><span class="line">		// 把图片保存到图片目录下</span><br><span class="line">		// 保存图片，这个图片的文件名可能会重复，为每个文件生成一个新的文件名</span><br><span class="line">		String picName = UUID.randomUUID().toString();</span><br><span class="line">		// 截图文件的扩展名</span><br><span class="line">		String oriName = picture.getOriginalFilename();</span><br><span class="line">		String extName = oriName.substring(oriName.lastIndexOf(&quot;.&quot;));</span><br><span class="line">		// 保存文件</span><br><span class="line">		picture.transferTo(new File(&quot;D:\\picture\\&quot; + picName + extName));</span><br><span class="line">		// 包文件名保存到数据库</span><br><span class="line">		item.setPic(picName+extName);</span><br><span class="line">		service.updateItem(item);</span><br><span class="line">		// 重定向</span><br><span class="line">//		return &quot;redirect:/itemList.action&quot;;</span><br><span class="line">		// 转向</span><br><span class="line">		return &quot;forward:/item/itemEdit.action&quot;;</span><br><span class="line">	&#125;</span><br></pre></td></tr></table></figure></p>
<p>######6). 修改ItemMapper.xml文件<br>将<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&lt;update id=&quot;updateItem&quot; parameterType=&quot;Item&quot;&gt;</span><br><span class="line">	update items set name=#&#123;name&#125;, price=#&#123;price&#125;, detail=#&#123;detail&#125; where id = #&#123;id&#125;</span><br><span class="line">&lt;/update&gt;</span><br></pre></td></tr></table></figure></p>
<p>修改为<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><span class="line">&lt;update id=&quot;updateItem&quot; parameterType=&quot;Item&quot;&gt;</span><br><span class="line">	update items set name=#&#123;name&#125;, price=#&#123;price&#125;, detail=#&#123;detail&#125;, pic=#&#123;pic&#125; where id = #&#123;id&#125;</span><br><span class="line">&lt;/update&gt;</span><br></pre></td></tr></table></figure></p>
<p>######7). 运行项目测试<br><img src="https://upload-images.jianshu.io/upload_images/3110861-1f759be09528ae9d.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图9.png"></p>
<p>####2. 前台的json数据交互</p>
<p>######1). 两种形式<br><img src="https://upload-images.jianshu.io/upload_images/3110861-26be10e5f91dcd43.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图10.png"></p>
<p>######2). <a href="http://www.java2s.com/Code/JarDownload/jackson-all/" target="_blank" rel="noopener">Jackson包</a><br><img src="https://upload-images.jianshu.io/upload_images/3110861-fe001ee78bf49fa6.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图11.png"></p>
<p>######3). 配置json转换器<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br></pre></td><td class="code"><pre><span class="line">&lt;!-- 用于将对象转换为 JSON  --&gt;  </span><br><span class="line">&lt;bean id=&quot;stringConverter&quot; class=&quot;org.springframework.http.converter.StringHttpMessageConverter&quot;&gt;  </span><br><span class="line">    &lt;property name=&quot;supportedMediaTypes&quot;&gt;  </span><br><span class="line">        &lt;list&gt;  </span><br><span class="line">            &lt;value&gt;text/plain;charset=UTF-8&lt;/value&gt;  </span><br><span class="line">        &lt;/list&gt;  </span><br><span class="line">    &lt;/property&gt;  </span><br><span class="line">&lt;/bean&gt;  </span><br><span class="line">&lt;bean id=&quot;jsonConverter&quot; class=&quot;org.springframework.http.converter.json.MappingJackson2HttpMessageConverter&quot;&gt;&lt;/bean&gt;  </span><br><span class="line"></span><br><span class="line">&lt;bean class=&quot;org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter&quot;&gt;  </span><br><span class="line">    &lt;property name=&quot;messageConverters&quot;&gt;  </span><br><span class="line">        &lt;list&gt;  </span><br><span class="line">            &lt;ref bean=&quot;stringConverter&quot; /&gt;  </span><br><span class="line">            &lt;ref bean=&quot;jsonConverter&quot; /&gt;  </span><br><span class="line">        &lt;/list&gt;  </span><br><span class="line">    &lt;/property&gt;  </span><br><span class="line">&lt;/bean&gt;</span><br></pre></td></tr></table></figure></p>
<p><strong>注意：如果使用&lt;mvc:annotation-driven /&gt;注解驱动的话就不用以上的配置</strong></p>
<p>######4). json交互的测试<br>I. 修改itemList.jsp，如下<br><a href="https://jquery.com/" target="_blank" rel="noopener">jQuery下载</a><br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br><span class="line">35</span><br><span class="line">36</span><br><span class="line">37</span><br><span class="line">38</span><br><span class="line">39</span><br><span class="line">40</span><br><span class="line">41</span><br><span class="line">42</span><br><span class="line">43</span><br><span class="line">44</span><br><span class="line">45</span><br><span class="line">46</span><br><span class="line">47</span><br><span class="line">48</span><br><span class="line">49</span><br><span class="line">50</span><br><span class="line">51</span><br><span class="line">52</span><br><span class="line">53</span><br><span class="line">54</span><br><span class="line">55</span><br><span class="line">56</span><br><span class="line">57</span><br><span class="line">58</span><br><span class="line">59</span><br><span class="line">60</span><br><span class="line">61</span><br><span class="line">62</span><br><span class="line">63</span><br><span class="line">64</span><br><span class="line">65</span><br><span class="line">66</span><br><span class="line">67</span><br><span class="line">68</span><br><span class="line">69</span><br><span class="line">70</span><br></pre></td><td class="code"><pre><span class="line">&lt;%@ page language=&quot;java&quot; contentType=&quot;text/html; charset=UTF-8&quot;</span><br><span class="line">	pageEncoding=&quot;UTF-8&quot;%&gt;</span><br><span class="line">&lt;%@ taglib uri=&quot;http://java.sun.com/jsp/jstl/core&quot; prefix=&quot;c&quot;%&gt;</span><br><span class="line">&lt;%@ taglib uri=&quot;http://java.sun.com/jsp/jstl/fmt&quot; prefix=&quot;fmt&quot;%&gt;</span><br><span class="line">&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD HTML 4.01 Transitional//EN&quot; &quot;http://www.w3.org/TR/html4/loose.dtd&quot;&gt;</span><br><span class="line">&lt;html&gt;</span><br><span class="line">	&lt;head&gt;</span><br><span class="line">		&lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=UTF-8&quot;&gt;</span><br><span class="line">		&lt;title&gt;查询商品列表&lt;/title&gt;</span><br><span class="line">		&lt;script type=&quot;text/javascript&quot; src=&quot;$&#123;pageContext.request.contextPath &#125;/js/jquery-3.3.1.min.js&quot;&gt;&lt;/script&gt;</span><br><span class="line">	&lt;/head&gt;</span><br><span class="line">	&lt;body&gt;</span><br><span class="line">		&lt;form action=&quot;$&#123;pageContext.request.contextPath &#125;/item/queryitem.action&quot; method=&quot;post&quot;&gt;</span><br><span class="line">			查询条件：</span><br><span class="line">			&lt;table width=&quot;100%&quot; border=&quot;1&quot;&gt;</span><br><span class="line">				&lt;tr&gt;</span><br><span class="line">					&lt;td&gt;商品id：&lt;input type=&quot;text&quot; name=&quot;item.id&quot; /&gt;&lt;/td&gt;</span><br><span class="line">					&lt;td&gt;商品名称：&lt;input type=&quot;text&quot; name=&quot;item.name&quot; /&gt;&lt;/td&gt;</span><br><span class="line">					&lt;td&gt;&lt;input type=&quot;submit&quot; value=&quot;查询&quot;/&gt;&lt;/td&gt;</span><br><span class="line">				&lt;/tr&gt;</span><br><span class="line">			&lt;/table&gt;</span><br><span class="line">			商品列表：</span><br><span class="line">			&lt;table width=&quot;100%&quot; border=&quot;1&quot;&gt;</span><br><span class="line">				&lt;tr&gt;</span><br><span class="line">					&lt;td&gt;选择&lt;/td&gt;</span><br><span class="line">					&lt;td&gt;商品名称&lt;/td&gt;</span><br><span class="line">					&lt;td&gt;商品价格&lt;/td&gt;</span><br><span class="line">					&lt;td&gt;生产日期&lt;/td&gt;</span><br><span class="line">					&lt;td&gt;商品描述&lt;/td&gt;</span><br><span class="line">					&lt;td&gt;操作&lt;/td&gt;</span><br><span class="line">				&lt;/tr&gt;</span><br><span class="line">				&lt;c:forEach items=&quot;$&#123;itemList &#125;&quot; var=&quot;item&quot; varStatus=&quot;s&quot;&gt;</span><br><span class="line">					&lt;%-- &lt;tr&gt;</span><br><span class="line">						&lt;td&gt;&lt;input type=&quot;checkbox&quot; name=&quot;ids&quot; value=&quot;$&#123;item.id &#125;&quot;/&gt;&lt;/td&gt;</span><br><span class="line">						&lt;td&gt;$&#123;item.name &#125;&lt;/td&gt;</span><br><span class="line">						&lt;td&gt;$&#123;item.price &#125;&lt;/td&gt;</span><br><span class="line">						&lt;td&gt;&lt;fmt:formatDate value=&quot;$&#123;item.createtime &#125;&quot; pattern=&quot;yyyy-MM-dd HH:mm:ss&quot;/&gt;&lt;/td&gt;</span><br><span class="line">						&lt;td&gt;$&#123;item.detail &#125;&lt;/td&gt;</span><br><span class="line">						&lt;td&gt;&lt;a href=&quot;$&#123;pageContext.request.contextPath &#125;/itemEdit.action?id=$&#123;item.id&#125;&quot;&gt;修改&lt;/a&gt;&lt;/td&gt;</span><br><span class="line">					&lt;/tr&gt; --%&gt;</span><br><span class="line">					&lt;tr&gt;</span><br><span class="line">						&lt;td&gt;&lt;input type=&quot;checkbox&quot; name=&quot;ids&quot; value=&quot;$&#123;item.id &#125;&quot;/&gt;&lt;/td&gt;</span><br><span class="line">						&lt;td&gt;</span><br><span class="line">							&lt;input type=&quot;hidden&quot; name=&quot;itemList[$&#123;s.index &#125;].id&quot; value=&quot;$&#123;item.id &#125;&quot;/&gt;</span><br><span class="line">							&lt;input type=&quot;text&quot; name=&quot;itemList[$&#123;s.index &#125;].name&quot; value=&quot;$&#123;item.name &#125;&quot;/&gt;</span><br><span class="line">						&lt;/td&gt;</span><br><span class="line">						&lt;td&gt;&lt;input type=&quot;text&quot; name=&quot;itemList[$&#123;s.index &#125;].price&quot; value=&quot;$&#123;item.price &#125;&quot;/&gt;&lt;/td&gt;</span><br><span class="line">						&lt;td&gt;&lt;input type=&quot;text&quot; name=&quot;itemList[$&#123;s.index &#125;].createtime&quot; value=&apos;&lt;fmt:formatDate value=&quot;$&#123;item.createtime &#125;&quot; pattern=&quot;yyyy-MM-dd HH:mm:ss&quot;/&gt;&apos;/&gt;&lt;/td&gt;</span><br><span class="line">						&lt;td&gt;&lt;input type=&quot;text&quot; name=&quot;itemList[$&#123;s.index &#125;].detail&quot; value=&quot;$&#123;item.detail &#125;&quot;/&gt;&lt;/td&gt;</span><br><span class="line">						&lt;td&gt;&lt;a href=&quot;$&#123;pageContext.request.contextPath &#125;/itemEdit.action?id=$&#123;item.id&#125;&quot;&gt;修改&lt;/a&gt;&lt;/td&gt;</span><br><span class="line">					&lt;/tr&gt;</span><br><span class="line">				&lt;/c:forEach&gt;</span><br><span class="line">			&lt;/table&gt;</span><br><span class="line">		&lt;/form&gt;</span><br><span class="line">		&lt;button onclick=&quot;sendJson()&quot;&gt;JSON数据交互测试&lt;/button&gt;</span><br><span class="line">		&lt;script type=&quot;text/javascript&quot;&gt;</span><br><span class="line">			function sendJson() &#123;</span><br><span class="line">				$.ajax(&#123;</span><br><span class="line">					type:&quot;post&quot;,</span><br><span class="line">					url:&quot;$&#123;pageContext.request.contextPath &#125;/jsonTest.action&quot;,</span><br><span class="line">					data:&apos;&#123;&quot;id&quot;:&quot;1&quot;,&quot;name&quot;:&quot;电冰箱&quot;,&quot;price&quot;:&quot;1999&quot;&#125;&apos;,</span><br><span class="line">					contentType:&quot;application/json;charset=utf-8&quot;,</span><br><span class="line">					success:function(data) &#123;</span><br><span class="line">						alert(data.id + &quot;:&quot; + data.name);</span><br><span class="line">					&#125;</span><br><span class="line">				&#125;);</span><br><span class="line">			&#125;</span><br><span class="line">		&lt;/script&gt;</span><br><span class="line">	&lt;/body&gt;</span><br><span class="line">&lt;/html&gt;</span><br></pre></td></tr></table></figure></p>
<p>II. 修改文件路径<br>将原在/WebContent/WEB-INF/路径下的css,image,js文件夹，移至/WebContent/路径下<br><img src="https://upload-images.jianshu.io/upload_images/3110861-8d3b3d1c10de4620.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图12.png"></p>
<p>III. 在ItemController中创建方法<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br></pre></td><td class="code"><pre><span class="line">// JSON数据交互</span><br><span class="line">// @RequestBody: 接收JSON数据并转换为pojo对象</span><br><span class="line">// @ResponseBody: 相应JSON数据，把POJO对象转换为JSON数据并响应</span><br><span class="line">@RequestMapping(&quot;/jsonTest&quot;)</span><br><span class="line">@ResponseBody</span><br><span class="line">public Item jsonTest(@RequestBody Item item)&#123;</span><br><span class="line">	System.out.println(item.toString());</span><br><span class="line">	return item;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>IV. 测试结果：<br>前台：<br><img src="https://upload-images.jianshu.io/upload_images/3110861-0b208ca49a4c7ba1.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图13.png"><br>后台：<br><img src="https://upload-images.jianshu.io/upload_images/3110861-0c254a7ab0a561a1.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图14.png"></p>
<p>####3. <a href="https://github.com/aisuhua/restful-api-design-references" target="_blank" rel="noopener">Restful</a></p>
<p>######1). <a href="http://www.ruanyifeng.com/blog/2014/05/restful_api.html" target="_blank" rel="noopener">设计指南</a><br>在Restful之前的操作：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">http://127.0.0.1/user/query/1 GET  根据用户id查询用户数据</span><br><span class="line">http://127.0.0.1/user/save POST 新增用户</span><br><span class="line">http://127.0.0.1/user/update POST 修改用户信息</span><br><span class="line">http://127.0.0.1/user/delete GET/POST 删除用户信息</span><br></pre></td></tr></table></figure></p>
<p>RESTful用法：<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">http://127.0.0.1/user/1 GET  根据用户id查询用户数据</span><br><span class="line">http://127.0.0.1/user  POST 新增用户</span><br><span class="line">http://127.0.0.1/user  PUT 修改用户信息</span><br><span class="line">http://127.0.0.1/user  DELETE 删除用户信息</span><br></pre></td></tr></table></figure></p>
<p>之前的操作是没有问题的,大神认为是有问题的,有什么问题呢?你每次请求的接口或者地址,都在做描述,例如查询的时候用了query,新增的时候用了save,其实完全没有这个必要,我使用了get请求,就是查询.使用post请求,就是新增的请求,我的意图很明显,完全没有必要做描述,这就是为什么有了restful.</p>
<p>######2). 编写Restful风格的代码<br>I. 修改itemList.jsp中<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&lt;td&gt;&lt;a href=&quot;$&#123;pageContext.request.contextPath &#125;/itemEdit.action?id=$&#123;item.id&#125;&quot;&gt;修改&lt;/a&gt;&lt;/td&gt;</span><br></pre></td></tr></table></figure></p>
<p>修改为<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br></pre></td><td class="code"><pre><span class="line">&lt;td&gt;&lt;a href=&quot;$&#123;pageContext.request.contextPath &#125;/itemEdit/$&#123;item.id&#125;&quot;&gt;修改&lt;/a&gt;&lt;/td&gt;</span><br></pre></td></tr></table></figure></p>
<p><img src="https://upload-images.jianshu.io/upload_images/3110861-6382fa8057a4cca0.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图15.png"></p>
<p>II. 在web.xml配置文件中新增<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><span class="line">&lt;servlet-mapping&gt;</span><br><span class="line">	&lt;servlet-name&gt;springmvc&lt;/servlet-name&gt;</span><br><span class="line">	&lt;!-- /：拦截所有请求，不包括jsp。/*：拦截所有请求，包括jsp，应该配置&quot;/&quot; --&gt;</span><br><span class="line">	&lt;url-pattern&gt;/&lt;/url-pattern&gt;</span><br><span class="line">&lt;/servlet-mapping&gt;</span><br></pre></td></tr></table></figure></p>
<p>III. 修改editItem的方法<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">@RequestMapping(&quot;/itemEdit/&#123;id&#125;&quot;)</span><br><span class="line">// 如果id和方法的形参一直，@PathVariable注解中可以不写内容</span><br><span class="line">public String editItem(@PathVariable(&quot;id&quot;)Integer ids, Model model)&#123;</span><br><span class="line">	// 调用服务</span><br><span class="line">	Item item = service.getItemById(ids);</span><br><span class="line">	// 把数据传递给页面，需要用到Model接口</span><br><span class="line">	model.addAttribute(&quot;item&quot;, item);</span><br><span class="line">	// 返回逻辑视图</span><br><span class="line">	return &quot;editItem&quot;;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>IV. 设置一下不让SpringMVC解析静态资源。SpringMVC的<code>&lt;mvc:resources mapping=&quot;&quot; location=&quot;&quot;&gt;</code>标签可实现对静态资源进行映射访问.<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><span class="line">&lt;!-- 配置资源映射 --&gt;</span><br><span class="line">&lt;mvc:resources location=&quot;/js/&quot; mapping=&quot;/js/**&quot;/&gt;</span><br><span class="line">&lt;mvc:resources location=&quot;/css/&quot; mapping=&quot;/css/**&quot;/&gt;</span><br><span class="line">&lt;mvc:resources location=&quot;/image/&quot; mapping=&quot;/image/**&quot;/&gt;</span><br></pre></td></tr></table></figure></p>
<p>V. 测试<br><img src="https://upload-images.jianshu.io/upload_images/3110861-a3425b8471ed00c6.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图16.png"></p>
<p>####4. 拦截器的定义和配置</p>
<p>######1). 定义：拦截器要实现HandlerInterceptor接口，并实现该接口中提供的三个方法<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br></pre></td><td class="code"><pre><span class="line">public class Interceptor1 implements HandlerInterceptor&#123;</span><br><span class="line">	@Override</span><br><span class="line">	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)</span><br><span class="line">			throws Exception &#123;</span><br><span class="line">		System.out.println(&quot;Interceptor1 preHandle......&quot;);</span><br><span class="line">		// 执行的时机是在Handler执行之前放行此方法</span><br><span class="line">		// 返回值：true，放行不拦截，正常执行Handler进行处理</span><br><span class="line">		// 返回值：false，拦截，Handler不能正常处理</span><br><span class="line">		return true;</span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">	@Override</span><br><span class="line">	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,</span><br><span class="line">			ModelAndView modelAndView) throws Exception &#123;</span><br><span class="line">		// Handler 执行之后，在返回ModelAndView之前，对modelAndView进行处理</span><br><span class="line">		System.out.println(&quot;Interceptor1 postHandle......&quot;);</span><br><span class="line">	&#125;</span><br><span class="line">	@Override</span><br><span class="line">	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)</span><br><span class="line">			throws Exception &#123;</span><br><span class="line">		// 返回ModelAndView之后</span><br><span class="line">		// Handler执行过程如果出现异常，可以在此处理异常</span><br><span class="line">		System.out.println(&quot;Interceptor1 afterCompletion......&quot;);</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<ul>
<li>preHandle方法：该方法执行的时机是在Handler执行之前执行。可以用于身份认证、身份授权等。比如如果认证没有通过表示用户没有登录，需要此方法拦截不再往下执行（return false），否则就放行（return true）。</li>
<li>postHandle方法：该方法执行的时机是在Handler执行之后，在返回ModelAndView之前执行，可以看到该方法中有个modelAndView的形参。应用场景：从modelAndView出发，将公用的模型数据（比如菜单导航之类的）在这里传到视图，也可以在这里统一指定视图。</li>
<li>afterCompletion方法：返回ModelAndView之后执行。应用场景：统一异常处理(即Handler执行过程中出现异常，可以在此处理异常)，统一日志处理等。<br>######2). 配置拦截器</li>
<li><p>某种HandlerMapping配置拦截器<br>在springmvc.xml文件中配置</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br></pre></td><td class="code"><pre><span class="line">&lt;bean class=&quot;org.springframework.web.servlet.handler.BeanNameUrlHandlerMapping&quot;&gt;</span><br><span class="line">    &lt;property name=&quot;interceptors&quot;&gt;</span><br><span class="line">        &lt;list&gt;</span><br><span class="line">            &lt;ref bean=&quot;handlerInterceptor1&quot;/&gt;</span><br><span class="line">            &lt;ref bean=&quot;handlerInterceptor2&quot;/&gt;</span><br><span class="line">        &lt;/list&gt;</span><br><span class="line">    &lt;/property&gt;</span><br><span class="line">&lt;/bean&gt;</span><br><span class="line">&lt;bean id=&quot;handlerInterceptor1&quot; class=&quot;com.mazaiting.interceptor.Interceptor1&quot;/&gt;</span><br><span class="line">&lt;bean id=&quot;handlerInterceptor2&quot; class=&quot;com.mazaiting.interceptor.Interceptor2&quot;/&gt;</span><br></pre></td></tr></table></figure>
</li>
<li><p>所有HandlerMapping配置全局拦截器<br>在springmvc.xml文件中配置</p>
<figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br></pre></td><td class="code"><pre><span class="line">&lt;!-- 配置拦截器 --&gt;</span><br><span class="line">&lt;mvc:interceptors&gt;</span><br><span class="line">    &lt;!-- 按照配置的顺序执行拦截器 --&gt;</span><br><span class="line">    &lt;mvc:interceptor&gt;</span><br><span class="line">        &lt;mvc:mapping path=&quot;/**&quot;/&gt;</span><br><span class="line">        &lt;bean class=&quot;com.mazaiting.interceptor.Interceptor1&quot;&gt;&lt;/bean&gt;</span><br><span class="line">    &lt;/mvc:interceptor&gt;</span><br><span class="line">    &lt;mvc:interceptor&gt;</span><br><span class="line">        &lt;mvc:mapping path=&quot;/**&quot;/&gt;</span><br><span class="line">        &lt;bean class=&quot;com.mazaiting.interceptor.Interceptor2&quot;&gt;&lt;/bean&gt;</span><br><span class="line">    &lt;/mvc:interceptor&gt;</span><br><span class="line">&lt;/mvc:interceptors&gt;</span><br></pre></td></tr></table></figure>
</li>
</ul>
<p><strong>注意：path=”/**”表示拦截所有的url包括子url路径。在实际开发中，一般我们都用这种配置，<a href="mvc:mapping" target="_blank" rel="noopener">mvc:mapping</a>中指定要拦截的url即可</strong></p>
<p>######3). 测试<br><img src="https://upload-images.jianshu.io/upload_images/3110861-4dafc229ef664840.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图17.png"><br><strong>总结：当所有拦截器都放行的时候，preHandle方法是按照配置的顺序执行的；而另外两个方法按照配置的顺序逆向执行。</strong></p>
<p>######4).有一个拦截器不放行<br><img src="https://upload-images.jianshu.io/upload_images/3110861-32dcf92e1629861c.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图18.png"></p>
<p><strong>总结</strong></p>
<ul>
<li>由于拦截器1和2放行，所以拦截器3的preHandle才能执行。也就是说前面的拦截器放行了，后面的拦截器才能执行preHandle方法。</li>
<li>拦截器3不放行，所以其另外两个方法没有被执行。即如果某个拦截器不放行，那么它的另外两个方法就不会被执行。</li>
<li>只要有一个拦截器不放行，所有拦截器的postHandle方法都不会执行，但是只要执行过preHandle并且放行的，就会执行afterCompletion方法。</li>
</ul>
<p>######5). 三个拦截器都不放行<br><img src="https://upload-images.jianshu.io/upload_images/3110861-e848fb394875a2ae.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240" alt="图19.png"><br><strong>总结</strong><br>总结</p>
<ul>
<li>preHandle按拦截器定义顺序调用</li>
<li>postHandler按拦截器定义逆序调用</li>
<li>afterCompletion按拦截器定义逆序调用</li>
<li>postHandler在拦截器链内所有拦截器返回true才调用</li>
<li>afterCompletion只有preHandle返回true才调用</li>
</ul>
<p>####5. 拦截器应用实例</p>
<p>######1). 编写login.jsp页面<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br></pre></td><td class="code"><pre><span class="line">&lt;%@ page language=&quot;java&quot; contentType=&quot;text/html; charset=UTF-8&quot;</span><br><span class="line">	pageEncoding=&quot;UTF-8&quot;%&gt;</span><br><span class="line">&lt;!DOCTYPE html PUBLIC &quot;-//W3C//DTD HTML 4.01 Transitional//EN&quot; &quot;http://www.w3.org/TR/html4/loose.dtd&quot;&gt;</span><br><span class="line">&lt;html&gt;</span><br><span class="line">	&lt;head&gt;</span><br><span class="line">		&lt;meta http-equiv=&quot;Content-Type&quot; content=&quot;text/html; charset=UTF-8&quot;&gt;</span><br><span class="line">		&lt;title&gt;登录&lt;/title&gt;</span><br><span class="line">	&lt;/head&gt;</span><br><span class="line">	&lt;body&gt;	</span><br><span class="line">		&lt;form action=&quot;$&#123;pageContext.request.contextPath &#125;/user/login&quot; method=&quot;post&quot;&gt;</span><br><span class="line">			&lt;label&gt;用户名&lt;/label&gt;</span><br><span class="line">			&lt;input type=&quot;text&quot; name=&quot;username&quot;/&gt;</span><br><span class="line">			&lt;br/&gt;</span><br><span class="line">			&lt;label&gt;密码&lt;/label&gt;</span><br><span class="line">			&lt;input type=&quot;password&quot; name=&quot;password&quot;/&gt;</span><br><span class="line">			&lt;br/&gt;</span><br><span class="line">			&lt;input type=&quot;submit&quot; value=&quot;提交&quot;/&gt;</span><br><span class="line">		&lt;/form&gt;</span><br><span class="line">	&lt;/body&gt;</span><br><span class="line">&lt;/html&gt;</span><br></pre></td></tr></table></figure></p>
<p>######2). 编写实现用户登录的Controller<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br></pre></td><td class="code"><pre><span class="line">@Controller</span><br><span class="line">@RequestMapping(&quot;/user&quot;)</span><br><span class="line">public class UserController &#123;</span><br><span class="line"></span><br><span class="line">	@RequestMapping(&quot;/showlogin&quot;)</span><br><span class="line">	public String showLogin()&#123;</span><br><span class="line">		return &quot;login&quot;;</span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">	@RequestMapping(&quot;/login&quot;)</span><br><span class="line">	public String userLogin(String username,String password, HttpSession session) &#123;</span><br><span class="line">		// 判断用户名和密码是否正确</span><br><span class="line">		System.out.println(username + &quot; ： &quot; + password);</span><br><span class="line">		// 正确，向session中写入用户信息</span><br><span class="line">		session.setAttribute(&quot;username&quot;, username);</span><br><span class="line">		// 返回登录成功页面，或者跳转至商品列表页面</span><br><span class="line">		return &quot;redirect:/itemList.action&quot;;</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>######3). 登录验证拦截器的实现<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br><span class="line">27</span><br><span class="line">28</span><br><span class="line">29</span><br><span class="line">30</span><br><span class="line">31</span><br><span class="line">32</span><br><span class="line">33</span><br><span class="line">34</span><br></pre></td><td class="code"><pre><span class="line">public class LoginInterceptor implements HandlerInterceptor&#123;</span><br><span class="line">	@Override</span><br><span class="line">	public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)</span><br><span class="line">			throws Exception &#123;</span><br><span class="line">		String uri = request.getRequestURL().toString();</span><br><span class="line">		// 如果用户未登录，则跳转到登录页面。跳转过程可能被拦截，所以要做判断</span><br><span class="line">		if (uri.contains(&quot;login&quot;)) &#123;</span><br><span class="line">			return true;</span><br><span class="line">		&#125;</span><br><span class="line">		System.out.println(&quot;LoginInterceptor preHandle...&quot;);</span><br><span class="line">		// 用户拦截请求，判断用户是否登录</span><br><span class="line">		HttpSession session = request.getSession();</span><br><span class="line">		String username = (String) session.getAttribute(&quot;username&quot;);</span><br><span class="line">		if (!&quot;&quot;.equals(username) &amp;&amp; null != username) &#123;</span><br><span class="line">			// 已经登录，放行</span><br><span class="line">			return true;</span><br><span class="line">		&#125;</span><br><span class="line">		// 如果用户未登录，则跳转到登录页面</span><br><span class="line">		response.sendRedirect(request.getContextPath() + &quot;/user/showlogin&quot;);</span><br><span class="line">		return false;</span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">	@Override</span><br><span class="line">	public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler,</span><br><span class="line">			ModelAndView modelAndView) throws Exception &#123;</span><br><span class="line">		System.out.println(&quot;LoginInterceptor postHandle...&quot;);</span><br><span class="line">	&#125;</span><br><span class="line">	</span><br><span class="line">	@Override</span><br><span class="line">	public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)</span><br><span class="line">			throws Exception &#123;</span><br><span class="line">		System.out.println(&quot;LoginInterceptor afterCompletion...&quot;);</span><br><span class="line">	&#125;</span><br><span class="line">&#125;</span><br></pre></td></tr></table></figure></p>
<p>######4). 配置拦截器<br><figure class="highlight plain"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br></pre></td><td class="code"><pre><span class="line">&lt;!-- 配置拦截器 --&gt;</span><br><span class="line">&lt;mvc:interceptors&gt;</span><br><span class="line">	&lt;!-- 配置登录拦截器 --&gt;</span><br><span class="line">	&lt;mvc:interceptor&gt;</span><br><span class="line">		&lt;mvc:mapping path=&quot;/**&quot;/&gt;</span><br><span class="line">		&lt;bean class=&quot;com.mazaiting.interceptor.LoginInterceptor&quot;/&gt;</span><br><span class="line">	&lt;/mvc:interceptor&gt;</span><br><span class="line">&lt;/mvc:interceptors&gt;</span><br></pre></td></tr></table></figure></p>
<p>###<a href="https://gitee.com/mazaiting/Ssm" target="_blank" rel="noopener">代码下载–a1ef7c916</a></p>

      
    </div>
    
    
    

    

    

    

    <footer class="post-footer">
      

      
      
      

      
        <div class="post-nav">
          <div class="post-nav-next post-nav-item">
            
              <a href="/blog/2018/08/06/JakartaEE-Framework/JakartaEE-Spring、MyBatis和SpringMVC的整合(一)/" rel="next" title="JakartaEE-Spring、MyBatis和SpringMVC的整合(一)">
                <i class="fa fa-chevron-left"></i> JakartaEE-Spring、MyBatis和SpringMVC的整合(一)
              </a>
            
          </div>

          <span class="post-nav-divider"></span>

          <div class="post-nav-prev post-nav-item">
            
              <a href="/blog/2018/08/06/JakartaEE-Framework/JakartaEE-Spring、MyBatis和SpringMVC的整合(二)/" rel="prev" title="JakartaEE-Spring、MyBatis和SpringMVC的整合(二)">
                JakartaEE-Spring、MyBatis和SpringMVC的整合(二) <i class="fa fa-chevron-right"></i>
              </a>
            
          </div>
        </div>
      

      
      
    </footer>
  </div>
  
  
  
  </article>



    <div class="post-spread">
      
    </div>
  </div>


          </div>
          


          

  



        </div>
        
          
  
  <div class="sidebar-toggle">
    <div class="sidebar-toggle-line-wrap">
      <span class="sidebar-toggle-line sidebar-toggle-line-first"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-middle"></span>
      <span class="sidebar-toggle-line sidebar-toggle-line-last"></span>
    </div>
  </div>

  <aside id="sidebar" class="sidebar">
    
    <div class="sidebar-inner">

      

      

      <section class="site-overview-wrap sidebar-panel sidebar-panel-active">
        <div class="site-overview">
          <div class="site-author motion-element" itemprop="author" itemscope itemtype="http://schema.org/Person">
            
              <img class="site-author-image" itemprop="image"
                src="/blog/images/avatar.jpeg"
                alt="凌浩雨" />
            
              <p class="site-author-name" itemprop="name">凌浩雨</p>
              <p class="site-description motion-element" itemprop="description">专业从事于移动端开发，Android与iOS均有涉及，主做Android开发与React Native开发</p>
          </div>

          <nav class="site-state motion-element">

            
              <div class="site-state-item site-state-posts">
              
                <a href="/blog/archives/">
              
                  <span class="site-state-item-count">393</span>
                  <span class="site-state-item-name">posts</span>
                </a>
              </div>
            

            

            

          </nav>

          

          

          
          

          
          

          

        </div>
      </section>

      

      

    </div>
  </aside>


        
      </div>
    </main>

    <footer id="footer" class="footer">
      <div class="footer-inner">
        <div class="copyright">&copy; <span itemprop="copyrightYear">2018</span>
  <span class="with-love">
    <i class="fa fa-user"></i>
  </span>
  <span class="author" itemprop="copyrightHolder">凌浩雨</span>

  
</div>


  <div class="powered-by">Powered by <a class="theme-link" target="_blank" href="https://hexo.io">Hexo</a></div>



  <span class="post-meta-divider">|</span>



  <div class="theme-info">Theme &mdash; <a class="theme-link" target="_blank" href="https://github.com/iissnan/hexo-theme-next">NexT.Pisces</a> v5.1.4</div>




        







        
      </div>
    </footer>

    
      <div class="back-to-top">
        <i class="fa fa-arrow-up"></i>
        
      </div>
    

    

  </div>

  

<script type="text/javascript">
  if (Object.prototype.toString.call(window.Promise) !== '[object Function]') {
    window.Promise = null;
  }
</script>









  












  
  
    <script type="text/javascript" src="/blog/lib/jquery/index.js?v=2.1.3"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fastclick/lib/fastclick.min.js?v=1.0.6"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/jquery_lazyload/jquery.lazyload.js?v=1.9.7"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/velocity/velocity.ui.min.js?v=1.2.1"></script>
  

  
  
    <script type="text/javascript" src="/blog/lib/fancybox/source/jquery.fancybox.pack.js?v=2.1.5"></script>
  


  


  <script type="text/javascript" src="/blog/js/src/utils.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/motion.js?v=5.1.4"></script>



  
  


  <script type="text/javascript" src="/blog/js/src/affix.js?v=5.1.4"></script>

  <script type="text/javascript" src="/blog/js/src/schemes/pisces.js?v=5.1.4"></script>



  
  <script type="text/javascript" src="/blog/js/src/scrollspy.js?v=5.1.4"></script>
<script type="text/javascript" src="/blog/js/src/post-details.js?v=5.1.4"></script>



  


  <script type="text/javascript" src="/blog/js/src/bootstrap.js?v=5.1.4"></script>



  


  




	





  





  












  





  

  

  

  
  

  

  

  

</body>
</html>
